<template>
  <div class="custom-auditor-select-wrap">
    <!-- <el-form :inline="true" :model="queryForm" style="padding-left: 24px" label-position="left" @submit.native.prevent>
      <el-form-item label-width="70px" style="margin-bottom: 10px">
        <el-input v-model="queryForm.name" clearable size="small" prefix-icon="el-icon-search" placeholder="请输入内容" class="input-width-select" @keyup.enter.native="queryClick" />
      </el-form-item>
    </el-form> -->
    <el-checkbox v-if="userList.items.length > 0" :value="isAllChecked" style="padding-left: 24px" @change="checkAllFun">全选</el-checkbox>
    <div :class="{'mobile-list': showMobilePage}" class="user-list">
      <template v-for="(item, index) in userList.items">
        <staff-select-item :key="index" :is-active="isChecked(item.id)" :info="item" @check="targetCheck($event, 'id')" />
      </template>
      <empty-state v-if="userList.items.length === 0" height="352px" text="暂无角色" dec="管理员还没有设置角色" />
    </div>
    <div v-if="!noRequest" class="pagination-area">
      <el-pagination
        v-if="userList.items.length > 0"
        :current-page="userList.page"
        :page-size="userList.perPage"
        :total="userList.total"
        :pager-count="5"
        :page-sizes="[20, 50, 100, 250, 500]"
        :layout="showMobilePage? 'prev, next' : 'prev, pager, next'"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>
<script>
import { getAuditorList, getAuditorButtonList } from '@/api/legal';
import StaffSelectItem from './staffSelectItem';
import ClearBtn from '@/components/Common/ClearBtn';
import EmptyState from './emptyState';
import { mapState } from 'vuex';
export default {
  name: 'CustomAuditorSelect',
  components: { StaffSelectItem, ClearBtn, EmptyState },
  props: {
    examineRoleId: {
      type: Number | String,
      default: -1
    },
    selectedAuditors: { // 最终选择的审批人
      type: Array,
      default: () => {
        return [];
      }
    },
    tagSelecteds: { // 显示的tag数据
      type: Array,
      default: () => {
        return [];
      }
    },
    isSubmitBtn: { // 入口是否从自定义提交按钮处来
      type: Boolean,
      default: false
    },
    extendParams: {
      type: Object,
      default: null
    },
    max: {
      type: Number,
      default: 50
    },
    noRequest: { // 不需要接口请求
      type: Boolean,
      default: false
    },
    defaultList: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      userListLoading: false,
      queryForm: {
        examineRoleId: '',
        name: ''
      },
      userList: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInint: true
      },
      page: 1,
      perPage: 10
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    isAllChecked() {
      const total = this.userList.items.length;
      let currentTime = 0; // 出现次数
      this.userList.items.forEach(item => {
        const { id } = item;
        if (id) {
          if (this.selectItemIds.indexOf(id) >= 0) currentTime++;
        }
      });
      return currentTime === total;
    },
    selectItemIds() {
      if (this.tagSelecteds.length > 0) {
        const temp = [];
        this.tagSelecteds.forEach(item => {
          if (item.hasOwnProperty('isDepartment') || item.hasOwnProperty('isRole')) { // 有isDepartment 证明是通过部门列表获取的值
            if (item.isDepartment) {
              temp.push(item.id);
            } else {
              temp.push(item.userId);
            }
          } else {
            temp.push(item.id);
          }
        });
        return temp;
      } else {
        return [];
      }
    }
  },
  watch: {
    examineRoleId: {
      handler(newVal, oldVal) {
        this.queryForm.examineRoleId = newVal;
        if (!this.noRequest) {
          this.getList(true);
        } else {
          this.userList.items = [...this.defaultList];
        }
      },
      immediate: true
    }
  },
  methods: {
    // 全选逻辑
    checkAllFun(val) {
      this.userList.items.forEach(item => {
        const param = { item, isChecked: val };
        setTimeout(() => {
          if (val) {
            if (this.selectItemIds.indexOf(item.id) < 0) {
              this.targetCheck(param, 'id');
            }
          } else {
            this.targetCheck(param, 'id');
          }
        }, 0);
      });
    },
    // 判断复选框是否选中
    isChecked(id) {
      return this.selectItemIds.indexOf(id) >= 0;
    },
    targetCheck(data, field) {
      const isCheck = data.isChecked;
      const item = data.item;
      const tempSelectItemIds = JSON.parse(JSON.stringify(this.selectItemIds));
      const tempSelectItems = JSON.parse(JSON.stringify(this.tagSelecteds));
      if (isCheck) {
        if (this.selectedAuditors.length >= this.max) {
          this.$message({
            type: 'warning',
            message: '选择超过限制'
          });
          return;
        }
        tempSelectItems.push(item);
        this.$emit('update:tagSelecteds', tempSelectItems);
        this.addStaff(item);
      } else {
        const curIndex = tempSelectItemIds.indexOf(item[field]);
        if (curIndex >= 0) {
          tempSelectItems.splice(curIndex, 1);
          this.$emit('update:tagSelecteds', tempSelectItems);
        }
        this.deleteStaff(item);
      }
    },
    // 添加员工逻辑
    addStaff(item) {
      const { id, userName, avatar, post, number } = item;
      const tempSelectUsers = JSON.parse(JSON.stringify(this.selectedAuditors));
      const param = {
        id,
        userName,
        avatar,
        post,
        number
      };
      tempSelectUsers.push(param);
      this.$emit('update:selectedAuditors', tempSelectUsers);
    },
    // 删除员工
    deleteStaff(item) {
      const { id } = item;
      const tempSelectUsers = JSON.parse(JSON.stringify(this.selectedAuditors));
      const selectUserIds = tempSelectUsers.map(jitem => jitem.id);
      const deleteIndex = selectUserIds.indexOf(id);
      if (deleteIndex >= 0) {
        tempSelectUsers.splice(deleteIndex, 1);
        this.$emit('update:selectedAuditors', tempSelectUsers);
      }
    },
    queryEmpty() {
      this.queryForm.name = '';
      this.getList();
    },
    queryClick() {
      this.getList(true);
    },
    getList(reset = false) {
      if (reset) this.page = 1;
      this.userListLoading = true;
      const params = { ...this.queryForm, page: this.page, perPage: this.perPage };
      if (this.extendParams) {
        Object.keys(this.extendParams).forEach(key => {
          params[key] = this.extendParams[key];
        });
      }
      const getUser = this.getUserList();
      getUser(params).then(res => {
        if (res.code === 200) {
          this.userList = res.data;
        }
        this.userListLoading = false;
      },
      result => {
        if (result.code === 503) {
          this.$emit('refresh');
        }
        this.userListLoading = false;
      });
    },
    getUserList() {
      const isSubmitBtn = this.isSubmitBtn;
      if (!isSubmitBtn) {
        return getAuditorList;
      } else {
        return getAuditorButtonList;
      }
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.getList(true);
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.getList();
    }
  }
};
</script>
<style lang="scss" scoped>
.custom-auditor-select-wrap {
  & ::v-deep {
    .el-input__inner {
      height: 32px;
      line-height: 32px;
      padding: 0 8px 0 26px;
      font-size: 12px;
      width: 250px;
      background-color: #F5F5F5;
      border: none;
      &::-webkit-input-placeholder {
        color: #999;
      }
    }
    .el-input__prefix {
      color: #6b6b6b;
      font-size: 14px;
    }
  }
  .mobile-list {
    height: 234px !important;
  }
  .user-list {
    height: 360px;
    @include scrollBar();
  }
  .pagination-area {
    display: flex;
    justify-content: center;
  }
}
</style>
